﻿using IOA.MES.Business;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace IOA.MES.Web.Controllers
{
    public class MaterialController : Controller
    {
        /// <summary>
        /// 物料分类管理
        /// </summary>
        public ActionResult MaterialCategoryMgr()
        {
            return View();
        }

        /// <summary>
        /// 查询物料类别列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryMaterialCategories(int page, int limit, string txtCategoryCode, string txtCategoryName)
        {
            var total = 0;
            var duties = new MaterialMgr().QueryMaterialCategories(page, limit, out total, txtCategoryCode, txtCategoryName);
            return Json(new ResultJson<object>(duties, total));
        }


        /// <summary>
        /// 查询分类树
        /// </summary>
        [HttpPost]
        public JsonResult QueryMaterialCategoryTree(string key)
        {
            key = (key ?? string.Empty).Trim();
            var categories = new MaterialMgr().QueryMaterialCategories();

            var tree = new List<TreeModel>();
            var parents = categories.Where(_ => _.Level == 1).OrderBy(_ => _.CategoryCode).ToList();
            foreach (var parent in parents)
            {
                var node = new TreeModel
                {
                    id = parent.PkId,
                    title = $"【{parent.CategoryCode}】{parent.CategoryName}",
                    field = "PkId"
                };
                node.children.AddRange(GetTreeModels(categories, parent.PkId, key));
                if (!node.children.Any() && !string.IsNullOrWhiteSpace(key) && !node.title.ToUpper().Contains(key.ToUpper()))
                {
                    continue;
                }
                tree.Add(node);
            }
            return Json(new ResultJson<List<TreeModel>>(tree));
        }
        private List<TreeModel> GetTreeModels(List<VProductCategory> models, int parentId, string key = "")
        {
            var nodes = models.Where(_ => _.ParentId == parentId).OrderBy(_ => _.CategoryCode).Select(_ => new TreeModel
            {
                id = _.PkId,
                title = $"【{_.CategoryCode}】{_.CategoryName}",
                field = "PkId"
            }).ToList();
            for (var i = 0; i < nodes.Count; i++)
            {
                nodes[i].children.AddRange(GetTreeModels(models, nodes[i].id, key));
                if (!nodes[i].children.Any() && !string.IsNullOrWhiteSpace(key) && !nodes[i].title.ToUpper().Contains(key.ToUpper()))
                {
                    nodes.RemoveAt(i);
                    i--;
                }
            }

            return nodes;
        }

        /// <summary>
        /// 删除物料类别
        /// </summary>
        [HttpPost]
        public JsonResult DeleteMaterialCategory(int Id)
        {
            try
            {
                new MaterialMgr().DeleteMaterialCategory(new VUser { PkId = Id, ModifyBy = BaseEnv.UserId });
                return Json(new ResultJson<object>());
            }
            catch (BizException ex)
            {
                return Json(new ResultJson<object>(ex.ErrCode, ex.Message));
            }
            catch (Exception ex)
            {
                return Json(new ResultJson<object>(500, ex.Message));
            }
        }

        /// <summary>
        /// 物料类别编辑页
        /// </summary>
        public ActionResult EditMaterialCategory(int pkId, int parentId = 0)
        {
            var categories = new MaterialMgr().QueryProductCategories();
            ViewBag.Categories = QueryCategorySelect(categories);
            ViewBag.ParentId = parentId;

            var category = pkId <= 0 ? null : categories.FirstOrDefault(_ => _.PkId == pkId);
            return View(category);
        }
        private List<TreeModel> QueryCategorySelect(List<VProductCategory> categories)
        {
            var tree = new List<TreeModel>();
            var parents = categories.Where(_ => _.Level == 1).ToList();
            foreach (var parent in parents)
            {
                var node = new TreeModel
                {
                    id = parent.PkId,
                    title = $"【{parent.CategoryCode}】{parent.CategoryName}",
                    field = "PkId"
                };
                node.children.AddRange(GetTreeModels(categories, parent.PkId, ""));
                tree.Add(node);
            }

            var categoryModels = new List<TreeModel> { new TreeModel { id = 0, title = "请选择" } };
            categoryModels.AddRange(DeTree(tree));
            return categoryModels;
        }
        private List<TreeModel> DeTree(List<TreeModel> nodes, int level = 1)
        {
            var hor = level <= 1 ? "" : "|";
            for (var i = 1; i < level; i++)
            {
                hor = hor + "—";
            }

            var result = new List<TreeModel>();
            foreach (var node in nodes)
            {
                result.Add(new TreeModel
                {
                    id = node.id,
                    title = $"{hor}{node.title}"
                });
                result.AddRange(DeTree(node.children, level + 1));
            }
            return result;
        }

        /// <summary>
        /// 物料编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditMaterialCategory(VProductCategory model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new MaterialMgr().EditMaterialCategory(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 物料管理
        /// </summary>
        public ActionResult MaterialMgr(int workshopId = 0)
        {
            return View();
        }

        /// <summary>
        /// 查询物料代码列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryMaterials(int page, int limit, int categoryId, string key)
        {
            var total = 0;
            var materials = new MaterialMgr().QueryMaterials(page, limit, out total, categoryId, key);
            return Json(new ResultJson<object>(materials, total));
        }

        /// <summary>
        /// 物料编辑页
        /// </summary>
        public ActionResult EditMaterial(int categoryId, int pkId)
        {
            var categories = new MaterialMgr().QueryProductCategories();
            var categoryTree = QueryCategorySelect(categories);
            categoryTree.RemoveAt(0);
            ViewBag.Categories = categoryTree;
            var category = categories.FirstOrDefault(_ => _.PkId == categoryId);
            var material = pkId <= 0 ? null : new MaterialMgr().GetMaterial(pkId);
            if (material != null)
            {
                category = categories.FirstOrDefault(_ => string.Equals(_.CategoryCode, material.CategoryCode, StringComparison.CurrentCultureIgnoreCase));
                categoryId = category?.PkId ?? 0;
                material.CategoryCode = categoryId.ToString();
            }
            ViewBag.CategoryId = categoryId;
            return View(material);
        }

        /// <summary>
        /// 物料编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditMaterial(VProduct model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new MaterialMgr().EditMaterial(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除物料代码
        /// </summary>
        [HttpPost]
        public JsonResult DeleteMaterial(int PkId)
        {
            try
            {
                new MaterialMgr().DeleteMaterialCode(new VUser { PkId = PkId, ModifyBy = BaseEnv.UserId });
                return Json(new ResultJson<object>());
            }
            catch (BizException ex)
            {
                return Json(new ResultJson<object>(ex.ErrCode, ex.Message));
            }
            catch (Exception ex)
            {
                return Json(new ResultJson<object>(500, ex.Message));
            }
        }
    }
}
